import prompt from '@ohos.prompt';
import featureAbility from '@ohos.ability.featureAbility';

const TAG = "[ServiceModel]";
let mRemote = null; //rpc远程对象
let connection = -1; // 连接码
export class ServiceModel {

    /**
     * 连接服务回调
     * @param element 元素名
     * @param remote rpc远程对象 rpc.IRemoteObject
     */
    onConnectCallback(element, remote) {
        console.log(`${TAG}onConnectLocalService onConnectDone element:${element}`)
        console.log(`${TAG}onConnectLocalService onConnectDone remote:${remote}`)
        mRemote = remote;
        if (mRemote === null) {
            prompt.showToast({
                message: '服务连接失败'
            })
            return;
        }
        prompt.showToast({
            message: '服务连接成功',
        })
    }

    onDisconnectCallback(element) {
        console.log(`${TAG}onConnectLocalService onDisconnectDone element:${element}`)
        prompt.showToast({
            message: '服务断开',
        })
    }

    onFailedCallback(code) {
        console.log(`${TAG}onConnectLocalService onFailed errCode:${code}`)
        prompt.showToast({
            message: `连接失败 :${code}`
        })
    }

    connectService(deviceId) {
        console.log(`${TAG} onConnectService begin deviceId:${deviceId}`)
        connection = featureAbility.connectAbility(
            {
                deviceId: deviceId,
                bundleName: 'com.nlas.focusgame',
                abilityName: 'com.example.entry.ServiceAbility',
            },
            {
                onConnect: this.onConnectCallback,
                onDisconnect: this.onDisconnectCallback,
                onFailed: this.onFailedCallback,
            },
        )
    }

    disconnectService() {
        console.log(`${TAG} onDisconnectService begin`)
        mRemote = null
        if (connection === -1) {
            prompt.showToast({
                message: 'onDisconnectService not connected yet'
            })
            return
        }
        featureAbility.disconnectAbility(connection)
        connection = -1
        prompt.showToast({
            message: 'onDisconnectService disconnect done'
        })
    }

    getRemoteObject() {
        return mRemote
    }
}